package com.example.consumer.service.strategy;

import com.example.common.Board;
import com.example.common.RandomUtils;

import java.util.*;

public class SquareStrategy implements Strategy {
    @Override
    public int[] insertOneNumber(Board board, List<char[][]> allResult) {
        int[][] squareCount = board.getSquareCount();
        int min = 9;
        for (int m = 0; m < squareCount.length; m++) {
            for (int n = 0; n < squareCount[0].length; n++) {
                if (squareCount[m][n] < min) {
                    min = squareCount[m][n];
                }
            }
        }
        List<String> square = new ArrayList<>();
        for (int m = 0; m < squareCount.length; m++) {
            for (int n = 0; n < squareCount[0].length; n++) {
                if (squareCount[m][n] == min) {
                    String s1 = m + "," + n;
                    square.add(s1);
                }
            }
        }
        String s2 = square.get(RandomUtils.getRandomInt(square.size()));
        String[] split = s2.split(",");
        int m2 = Integer.parseInt(split[0]);
        int n2 = Integer.parseInt(split[1]);

        char[][] board1 = board.getBoard();
        Map<String, Set<Character>> map = new HashMap<>();
        for (int i = 3*m2; i < 3*m2+3; i++) {
            for (int j = 3*n2; j < 3*n2+3; j++) {
                if (board1[i][j] == '.') {
                    String s1 = i + "@" + j;
                    map.put(s1, new HashSet<>());
                }
            }
        }
        for (char[][] result1 : allResult) {
            for (int i = 3*m2; i < 3*m2+3; i++) {
                for (int j = 3*n2; j < 3*n2+3; j++) {
                    if (board1[i][j] == '.') {
                        String s1 = i + "@" + j;
                        map.get(s1).add(result1[i][j]);
                    }
                }
            }
        }
        return chooseFromMap(board, map);
    }
}
